<?php
    session_start();
    include('conn.php');
    $item_id = $_POST['deleteItem_id'];
    
    include('verify_user.php');
    require 'anti_csrf.php';

    if (!isset($_POST['CSRFName'])) {
        trigger_error("No CSRFName found, probable invalid request.",E_USER_ERROR);
    }
    $name =$_POST['CSRFName'];
    $token=$_POST['CSRFToken'];
    if (!csrfguard_validate_token($name, $token)) {
        trigger_error("Invalid CSRF token.",E_USER_ERROR);
    }

    $query = "SELECT shops.shop_owner FROM shops INNER JOIN items ON items.item_shop=shops.shop_name WHERE items.item_id=$1";
    pg_prepare($con, 'verifyowner', $query) or die('Could not prepare verifyowner');
    $rs = pg_execute($con, 'verifyowner', array($item_id)) or die("Fail to identify item owner");
    $row = pg_fetch_assoc($rs);
     
    if($cur_user != $row['shop_owner']) {
        die("Only owner can access!");
    }
    
    $query = "SELECT max(id) id FROM log";
    $rs = pg_query($con, $query) or die("Could not excute query");
    $row = pg_fetch_assoc($rs);
    $id = $row['id'] + 1;
    
    $query = "SELECT * FROM items WHERE item_id=$1";
    pg_prepare($con, 'getitemname', $query) or die('Could not prepare getitemname');
    $res0 = pg_execute($con, 'getitemname', array($item_id)) or die('Could not execute getitemname');
    $row = pg_fetch_assoc($res0);
    $item_name = $row['item_name'];
    $item_shop = $row['item_shop'];
    
    $query = "DELETE FROM items WHERE item_id=$1";
    $log_query = "INSERT INTO log VALUES($1 ,$2 ,$3 ,$4 ,$5)";
    pg_prepare($con,'prepare2',$query) or die('Could not prepare statement');
    pg_prepare($con,'log_prepare2',$log_query) or die('Could not prepare log statement');
    $res1 = pg_execute($con, 'prepare2', array($item_id)) or die('Could not execute query');
    $res2 = pg_execute($con, 'log_prepare2', array($cur_user, 'Delete Item',$item_name, date('Y-m-d'), $id)) or die ('Could not execute log query');
    
    if ($res1 && $res2) {
        pg_query('COMMIT') or die('Could not commit');
    } else {
        pg_query('ROLLBACK') or die('Could not rollback');
    }
    pg_close($con);
    header("Location:shop.php?id=" . $cur_user . "&shop=" . $item_shop);
?>
